package com.gzhryc.net_marketing.cloud.logistics.scfegine;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.cloud.logistics.ELogisticsState;
import com.gzhryc.net_marketing.cloud.logistics.LogisticsInfo;
import com.gzhryc.net_marketing.cloud.logistics.LogisticsSearchAPIService;

/**
 * 四川涪擎大数据技术有限公司
 * 阿里云购买全国物流信息查询
 * @version 2022-01-31
 */
public class FJLogisticsSearchAPIService implements LogisticsSearchAPIService {

    static Logger log = Logger.getLogger(FJLogisticsSearchAPIService.class);

    CloseableHttpClient httpClient;

    private String appCode = "57d62edef1494528bbd9646f06eefc66";

    public FJLogisticsSearchAPIService(){
        this.httpClient = HttpClients.createDefault();
    }

    @Override
    public LogisticsInfo search(String logisticsTradeNo, String logisticsCompanyId) throws LogicException{
        CloseableHttpResponse response = null;
        String companyCode = logisticsCompanyId;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            URI uri = new URIBuilder("https://wuliu.market.alicloudapi.com/kdi")
                    .setParameter("no",logisticsTradeNo)
                    .setParameter("type",companyCode != null?companyCode:"")
                    .build();

            HttpGet httpPost = new HttpGet(uri);
            httpPost.setHeader("Authorization","APPCODE " + appCode);

            response = httpClient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if(status == 200) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                    if(StringUtils.isNotBlank(str)) {
                        FJLogisticsInfo fjLogisticsInfo = JsonTools.fromJson(str, FJLogisticsInfo.class);
                        if ("0".equals(fjLogisticsInfo.getStatus())){
                            LogisticsInfo result = new LogisticsInfo();

                            result.setLogisticsTradeNo(fjLogisticsInfo.getResult().getNumber());
                            if("0".equals(fjLogisticsInfo.getResult().getDeliverystatus())){
                                result.setLogisticsState(ELogisticsState.ExpressReceipt.index());
                            }else if("1".equals(fjLogisticsInfo.getResult().getDeliverystatus())){
                                result.setLogisticsState(ELogisticsState.DuringTransportation.index());
                            }else if("2".equals(fjLogisticsInfo.getResult().getDeliverystatus())){
                                result.setLogisticsState(ELogisticsState.SendingMail.index());
                            }else if("3".equals(fjLogisticsInfo.getResult().getDeliverystatus())){
                                result.setLogisticsState(ELogisticsState.SignedIn.index());
                            }else if("4".equals(fjLogisticsInfo.getResult().getDeliverystatus())){
                                result.setLogisticsState(ELogisticsState.DeliveryFailed.index());
                            }else if("5".equals(fjLogisticsInfo.getResult().getDeliverystatus())){
                                result.setLogisticsState(ELogisticsState.DifficultParts.index());
                            }else if("6".equals(fjLogisticsInfo.getResult().getDeliverystatus())){
                                result.setLogisticsState(ELogisticsState.ReturnReceipt.index());
                            }

                            try{
                                Date lastUpdateDate = DateUtils.parseDate(fjLogisticsInfo.getResult().getUpdateTime()
                                        ,"yyyy-MM-dd HH:mm:ss");
                                result.setLastUpdateDate(lastUpdateDate);
                            }catch (Exception e){
                                log.error("时间转化错误：" + e.getMessage(),e);
                            }

                            result.setUseTimeStr(fjLogisticsInfo.getResult().getTakeTime());
                            if(fjLogisticsInfo.getResult().getList() != null
                                    && fjLogisticsInfo.getResult().getList().size() > 0) {
                                result.setTimeItems(new ArrayList<>());
                                for (FJLogisticsInfo.TimeItem timeItem : fjLogisticsInfo.getResult().getList()) {
                                    try {
                                        Date time = DateUtils.parseDate(timeItem.getTime()
                                                , "yyyy-MM-dd HH:mm:ss");

                                        LogisticsInfo.TimeItem item = new LogisticsInfo.TimeItem();
                                        item.setTime(time);
                                        item.setContent(timeItem.getStatus());
                                        result.getTimeItems().add(item);
                                    } catch (Exception e) {
                                        log.error("时间转化错误：" + e.getMessage(), e);
                                    }
                                }
                            }
                            return result;
                        }else if(StringUtils.isNotBlank(fjLogisticsInfo.getMsg())){
                            throw new LogicException(fjLogisticsInfo.getMsg());
                        }
                    }
                }
            }
        } catch (LogicException e){
            throw e;
        }catch(Exception e){
            log.error(e.getMessage(),e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
